import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Creater with IntelliJ IDEA.
 * Description:
 * User: 86152
 * Dae: 2022-08-07
 * Time: 23:08
 */
public class UdpEchoServer {
    private DatagramSocket socket= null;
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {

        while(true) {
            //1.接受请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            //2.解析请求
            String request = new String(requestPacket.getData(),0, requestPacket.getLength());
            //3.响应
            String response = process(request);
            //4.打包
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());
            //5.发送
            socket.send(responsePacket);
            System.out.printf("请求：%s   响应：%s",request,response);
        }
    }
    public String process(String req) {
        return req;
    }
}
